add(1,2); // 因為 function declaration hoist 的關係,所以可被執行
function add(a,b){
return a+b;
}
add(1,2); // 會出現 add is not defined
const add = function(a,b){
return a+b;
}
javascript 的 scope 為 static scoping,意即在函式建立時,作用域就被確定了
現在多數的程式語言都是 static scoping 為主
global scope
let variable_in_global = 10;
console.log(variable_in_global); // 10
function scope
function doSomething(){
let variable_in_function_scope = "can only access in function scope";
}
console.log(variable_in_function_scope); // variable_in_function_scope is not defined
有時候會需要引入新的作用域,像是要避免變數成為全域變數
這時候可以藉由 **IIFE (immediately invoked function expression) ** 來達成,一種將函式以類似block 使用的模式(using function in a block-like manner)
因為函式會建立自身的作用域
(function () { // open IIFE
let tmp = ...; // not a global variable
}());
這樣 tmp 就不會是 global variable
主要可減少程式碼長度,但需要注意的是 arrow function not bind their own this keyword
arrow function 的 this 是由建立的作用域繼承(inherit)而來
如果在 global scope 內建立 arrow function,則 this 會是 window object
const doSomething = () => {
console.log(this); // this -> window object
};
如果在 object 內建立的 arrow function,其 this 則為建立的作用域繼承來,所以便會是 object
let worker = {
name: "James",
workerMethod() {
const greeting = () => console.log(`${this.name} says hello`);
greeting();
},
};
worker.workerMethod(); // James says hello
提供函式的預設參數,直接在 curly braces 內 assign value
function (salary=28590 , bonus){
console.log(`薪水有:${salary + bonus}元`)
}
當傳入函式的 parameter 過多,會自動忽略
當傳入函式的 parameter 太少,則會用 undefined 來補足缺失的參數
善用 arguments.length
function pair(a,b){
if (arguments.length !== 2){
console.error("Need exactly 2 arguments");
}
...
}
帶有 return 的 pure function
function add(a,b){
return a+b;
}
沒有 return 的 pure function
const add = (a,b)=> a+b
會改變外部狀態的都可稱之為副作用,如:console, modified global variables, network request..
let total = 0;
function addToTotal(num){
total += num;
}